package com.ikun.aimian.scoring;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ikun.aimian.model.dto.question.QuestionContentDTO;
import com.ikun.aimian.model.entity.App;
import com.ikun.aimian.model.entity.Question;
import com.ikun.aimian.model.entity.ScoringResult;
import com.ikun.aimian.model.entity.UserAnswer;
import com.ikun.aimian.model.vo.QuestionVO;
import com.ikun.aimian.service.QuestionService;
import com.ikun.aimian.service.ScoringResultService;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * 自定义打分类应用评分策略
 *
 */
@ScoringStrategyConfig(appType = 0, scoringStrategy = 0)
public class CustomScoreScoringStrategy implements ScoringStrategy {

    @Resource
    private QuestionService questionService;

    @Resource
    private ScoringResultService scoringResultService;

    @Override
    public UserAnswer doScore(List<String> choices, App app) throws Exception {
        Long appId = app.getId();

        // 1. 根据 id 查询到题目和题目结果信息（按分数降序排序）
        Question question = questionService.getOne(
                Wrappers.lambdaQuery(Question.class).eq(Question::getAppId, appId)
        );

        List<ScoringResult> scoringResultList = scoringResultService.list(
                Wrappers.lambdaQuery(ScoringResult.class)
                        .eq(ScoringResult::getAppId, appId)
                        .orderByDesc(ScoringResult::getResultScoreRange)  // 按得分区间降序排列
        );

        // 2. 统计用户的总得分
        int totalScore = 0;
        QuestionVO questionVO = QuestionVO.objToVo(question);
        List<QuestionContentDTO> questionContent = questionVO.getQuestionContent();

        // 遍历题目列表
        for (int i = 0; i < questionContent.size(); i++) {
            QuestionContentDTO questionContentDTO = questionContent.get(i);

            // 获取当前题目的用户答案
            String userAnswer = choices.get(i);

            // 遍历该题目的选项，检查用户选择的答案
            boolean answerMatched = false;  // 标记是否找到匹配的答案
            for (QuestionContentDTO.Option option : questionContentDTO.getOptions()) {
                // 如果用户选择的答案与当前选项的 key 匹配
                if (option.getKey().equals(userAnswer)) {
                    int score = Optional.of(option.getScore()).orElse(0);
                    totalScore += score;  // 累加分数
                    answerMatched = true;

                    // 输出题目和匹配的答案及得分
//                    System.out.println("题目: " + questionContentDTO.getTitle());
//                    System.out.println("用户选择的答案: " + userAnswer);
//                    System.out.println("匹配答案: " + option.getKey() + ", 得分: " + score);
                    break;  // 一旦找到匹配答案，就退出当前题目的选项循环，避免重复计分
                }
            }

            // 如果没有找到匹配的答案，可以输出未匹配的提示
            if (!answerMatched) {
                System.out.println("题目: " + questionContentDTO.getTitle() + "，没有找到匹配的答案.");
            }
        }

        // 输出最终的得分
//        System.out.println("最终得分: " + totalScore);



        // 3. 找到第一个符合条件的评分结果：得分大于等于 resultScoreRange
        ScoringResult selectedScoringResult = null;
        for (ScoringResult scoringResult : scoringResultList) {
            if (totalScore >= scoringResult.getResultScoreRange()) {
                selectedScoringResult = scoringResult;
                break;  // 找到第一个符合条件的评分结果后跳出循环
            }
        }

        // 如果没有找到符合条件的评分结果，设置默认评分结果
        if (selectedScoringResult == null) {
            selectedScoringResult = scoringResultList.isEmpty() ? null : scoringResultList.get(scoringResultList.size() - 1);  // 默认最后一个评分结果
        }

        // 4. 构造返回值，填充答案对象的属性
        UserAnswer userAnswer = new UserAnswer();
        userAnswer.setAppId(appId);
        userAnswer.setAppType(app.getAppType());
        userAnswer.setScoringStrategy(app.getScoringStrategy());
        userAnswer.setChoices(JSONUtil.toJsonStr(choices));
        if (selectedScoringResult != null) {
            userAnswer.setResultId(selectedScoringResult.getId());
            userAnswer.setResultName(selectedScoringResult.getResultName());
            userAnswer.setResultDesc(selectedScoringResult.getResultDesc());
            userAnswer.setResultPicture(selectedScoringResult.getResultPicture());
        }
        userAnswer.setResultScore(totalScore);

        return userAnswer;
    }
}
